<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 头部 -->
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card v-loading="loading">
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="头像" width="200">
            <template slot-scope="scope">
              <img v-imgerror="require('@/assets/common/head.jpg')" :src="scope.row.staffPhoto" alt="" class="avatar" @click="showQRCode(scope.row.staffPhoto)">
            </template>
          </el-table-column>
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatEmployment" />
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable prop="timeOfEntry">
            <template slot-scope="obj">
              {{
                obj.row.timeOfEntry | formatDate
              }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" align="center" sortable="" prop="enableState">
            <template slot-scope="{ row }">
              <!-- 根据当前状态来确定 是否打开开关 -->
              <el-switch :value="row.enableState === 1" />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="assignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmployee(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="sizes, prev, pager, next, jumper, total"
            :page-sizes="[2, 5, 10, 50]"
            :page-size="page.size"
            :current-page="page.page"
            :total="page.total"
            @current-change="changePage"
            @size-change="sizeChang"
          />
        </el-row>
      </el-card>

      <!-- 弹层 -->
      <add-employee :show-dialog.sync="showDialog" />
      <!-- 角色弹层 -->
      <assign-role ref="assignRole" :user-id="userId" :show-role-dialog.sync="showRoleDialog" />
      <!-- 头像二维码弹层 -->
      <el-dialog title="头像二维码" :visible.sync="isShowQRCode">
        <el-row type="flex" justify="center">
          <canvas ref="QRCodeCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnums from '@/api/constant/employees'
import QRCode from 'qrcode'
// 我们需要用到过滤器函数中处理日期的功能, 但是又不是作为过滤器使用
// 单独引入函数, 将它当做普通函数使用即可
import { formatDate } from '@/filters'
import addEmployee from './components/add-employee.vue'
import AssignRole from './components/assign-role.vue'
export default {
  components: {
    addEmployee,
    AssignRole
  },
  data() {
    return {
      loading: false, // 加载状态
      list: [], // 接数据的
      page: {
        page: 1, // 当前页码
        size: 10, // 每页显示多少页
        total: 0 // 总数
      },
      showDialog: false,
      isShowQRCode: false,

      // 定义设定角色弹窗显示与否
      showRoleDialog: false,
      // 被点击的员工id
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    // 显示二维码
    showQRCode(photoURL) {
      if (photoURL) {
        // 1. 弹窗
        this.isShowQRCode = true
        // 2. 生成二维码放入 canvas 当中
        this.$nextTick(() => {
          QRCode.toCanvas(this.$refs.QRCodeCanvas, photoURL, {
            width: 300,
            color: {
              dark: '#66b1ff'
            }
          })
        })
      }
    },
    // 改变每页显示多少页
    sizeChang(newSize) {
      this.page.size = newSize
      this.getEmployeeList()
    },
    // 改变页码
    changePage(newPage) {
      this.page.page = newPage
      this.getEmployeeList()
    },
    // 获取员工列表
    async  getEmployeeList() {
      this.loading = true
      const { total, rows } = await getEmployeeList(this.page)
      console.log(total, rows)
      this.page.total = total
      this.list = rows
      this.loading = false
    },
    formatEmployment(row, column, cellValue) {
      // console.log(row, '----', column, '----', cellValue)
      // 要去找 1所对应的值
      const obj = EmployeeEnums.hireType.find(item => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    // 导出表格
    exportData() {
      // 懒加载
      import('@/vendor/Export2Excel').then(async excel => {
        // console.log('加载成功')
        console.log(excel)
        // const header = ['姓名', '年龄', '性别']
        // const data = [
        //   ['jack', 11, '男'],
        //   ['rose', 22, '女'],
        //   ['tom', 33, '男'],
        //   ['jerry', 44, '男']
        // ]
        // 1 加载所有员工数据
        const { rows } = await getEmployeeList({ page: 1, size: this.page.total })
        console.dir(rows)
        // 2 准备字典
        const headerDict = {
          '姓名': 'username',
          '手机号': 'mobile',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '转正日期': 'correctionTime',
          '工号': 'workNumber',
          '部门': 'departmentName'
        }
        // 3 根据字典生成表头
        const header = Object.keys(headerDict)
        console.log('表头', header)
        //  我们的 api 获取的数据是数组套 最终想要的是数组套数组
        // 4 遍历所有员工转换成数组套数组
        const newUserArray = rows.map(user => {
          // 这里相信之前已经创建了一个将用户对象转成用户数组的函数
          // 直接拿来用, 遍历所有的员工, 都变成数组形式
          return this.obj2array(user, headerDict)
        })
        console.log(newUserArray)

        excel.export_json_to_excel({
          header,
          data: newUserArray
        })
      })
    },
    // 对象转数组
    obj2array(user, dict) {
      console.log(user, dict)
      // 创建一个数组存放用户数据
      const arr = []
      // 按顺序遍历表头
      for (const key in dict) {
        // 拿到表头中文对应的英文 key
        const enKey = dict[key]
        console.log(enKey)
        // 对应英文 key 在用户数据中拿值
        let value = user[enKey]
        // 之前将 value 直接拿到即可,现在由于需要独立处理聘用形式和时间格式
        // 需要进行判断
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          value = value ? formatDate(value) : '未录入'
        } else if (enKey === 'formOfEmployment') {
          const obj = EmployeeEnums.hireType.find(item => item.id === value)
          value = obj ? obj.value : '未知'
        }
        // 放入数组中
        arr.push(value)
      }
      return arr
    },
    // 删除员工按钮
    async  delEmployee(id) {
      console.log(id)
      try {
        await this.$confirm('要删除吗?')
        await delEmployee(id)
        if (this.page.page !== 1 && this.list.length === 1) {
          console.log(123)
          this.page.page--
        }
        this.getEmployeeList()
        this.$message.success('删除成功')
      } catch (error) {
        console.log(error)
      }
    },
    // 点击角色按钮
    async assignRole(id) {
      await this.$refs.assignRole.getUserDetailById(id)
      this.showRoleDialog = true
      this.userId = id
    }
  }
}
</script>

<style>
.avatar {
  width: 200px;
  height: 200px;
  object-fit: cover;
}
</style>
